﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.OleDb;
using System.Data;
using System.Collections;
using System.Threading;


namespace ServerGps
{
    class AccessService
    {
        static OleDbConnection connection;
        private AccessService() {
            
            
        }
        static void initConn() {
            String connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Program Files\\txtSms\\smsdb.mdb";
            connection = new OleDbConnection(connectionString);
            connection.Open();
        }
        static void closeConn() {
            connection.Close();
        }
        static ArrayList getNewSms() {
            //initConn();
            ArrayList arr = new ArrayList();
            string sql = "select PhoneNumber, SmsContent from SmsRecordTable where state = 0";
            OleDbCommand cmd = new OleDbCommand(sql, connection);
            OleDbDataReader reader = cmd.ExecuteReader();
            while (reader.Read()) {
                string[] sms = new string[2];
                sms[0] = reader.GetString(0);
                sms[1] = reader.GetString(1);
                arr.Add(sms);
            }
            reader.Close();
            return arr;
        }
        static void setState() {
            string sql = "update SmsRecordTable set state = 1";
            OleDbCommand cmd = new OleDbCommand(sql, connection);
            cmd.ExecuteNonQuery();
            //closeConn();
        }
        public static void sendSms(string PhoneNumber, string Content) {
            string sql = "insert into WaitToSendSmsTable(SmsTime, PhoneNumber, SmsOperator, SmsContent, Status, FastSms, NewFlag) values('" + DateTime.Now.ToString() + "', '" + PhoneNumber + "', '系统管理员', '" + Content + "', '定时', '0', 0)";
            OleDbCommand cmd = new OleDbCommand(sql, connection);
            cmd.ExecuteNonQuery();
        }
        public static void Main() {
            initConn();
            while (true) {
                ArrayList arr = getNewSms();
                for (int i = 0; i < arr.Count; ++i) {
                    try
                    {
                        string[] sms = (string[])arr[i];
                        Service.getInstance().ProcessMsgRecved(sms[0], sms[1]);
                    }
                    catch (Exception ex) {
                        Console.WriteLine("处理错误 " + ex.ToString());
                        sendSms("13701358547", "短信猫2出错 " + ex.ToString());
                    }
                }
                setState();
                Thread.Sleep(5000);
            }
        }
    }
}
